﻿MPT.addObject('Util', function() {

    var othis = this;

    this.GetHashParam = function() {
        var hash = window.location.hash;
        var hash_strs = hash.split('/');
        return hash_strs[3] || "";
    };

    //键盘监控
    this.KeyBoardMonitor = this.MptKeyUp = function(_elm, _keyCode, _fun) {
        jQuery(_elm).keyup(function(e) {
            if (e.keyCode == _keyCode) {
                _fun();
            }
        });
    };

    //获得头像地址
    //userSpaceId: 用户ID
    //imgSize: 不传参数为100x100的头像；传入33为50x50的头像；传入16为25x25的头像
    this.avatarPath = function(userSpaceId, imgSize) {
        var avatarFolder = 1;
        if (userSpaceId > 0 && userSpaceId % 10000 == 0) {
            avatarFolder = (userSpaceId / 10000);
        } else {
            avatarFolder = (userSpaceId / 10000 + 1);
        }
        avatarFolder = avatarFolder.toString();

        if (imgSize != undefined) {
            return "/avatar/" + avatarFolder.substring(0, avatarFolder.indexOf(".")) + "/" + userSpaceId + "_" + imgSize + ".pjpeg" + '?' + Math.random();
        } else {
            return "/avatar/" + avatarFolder.substring(0, avatarFolder.indexOf(".")) + "/" + userSpaceId + ".pjpeg" + '?' + Math.random();
        }
    };

    //获得他人空间的地址
    //userSpaceId: 用户ID
    this.spacePath = function(userSpaceId) {

        return MPT.Config["hash"]["uspace"] + "/" + userSpaceId;
    };

    //截断字符串，被截断的部分用..补充
    //name：名称
    //reserveCount：保留几个字符
    this.truncName = function(name, reserveCount) {

        if (name == '' || name == undefined || name == null) return;

        if (name.length <= reserveCount) {
            return name;

        } else {
            return name.substr(0, reserveCount) + '..';
        }
    };


    //---------------------------跟时间有关的工具---------------------------------
    Date.prototype.format1 = function(format) {
        var o = {
            "M+": this.getMonth() + 1,
            "d+": this.getDate(),
            "h+": this.getHours(),
            "m+": this.getMinutes(),
            "s+": this.getSeconds(),
            "q+": Math.floor((this.getMonth() + 3) / 3),
            "S": this.getMilliseconds()
        }
        if (/(y+)/.test(format)) {
            format = format.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
        }
        for (var k in o) {
            if (new RegExp("(" + k + ")").test(format)) {
                format = format.replace(RegExp.$1, RegExp.$1.length == 1 ? o[k] : ("00" + o[k]).substr(("" + o[k]).length));
            }
        }
        return format;
    }

    /**
    * 过滤左右空格
    */
    String.prototype.Trim = function() {
        return this.replace(/(^\s*)|(\s*$)/g, "");
    };

    String.prototype.contains = function(substr, isIgnoreCase) {
        var preStr = this;
        if (isIgnoreCase) {
            preStr = preStr.toLowerCase();
            substr = substr.toLowerCase();
        }

        var startChar = substr.substring(0, 1);
        var strLen = substr.length;
        for (var j = 0; j < preStr.length - strLen + 1; j++) {
            if (preStr.charAt(j) == startChar)//如果匹配起始字符,开始查找
            {
                if (preStr.substring(j, j + strLen) == substr)//如果从j开始的字符与str匹配，那ok
                {
                    return true;
                }
            }
        }
        return false;
    };


    //    String.prototype.isNocontent = function() {
    //        return (this == '' || this == null || this == undefined);
    //    };

    /**  
    *转换日期对象为日期字符串  
    * @param date 日期对象  
    * @param isFull 是否为完整的日期数据,  
    *               为true时, 格式如"2000-03-05 01:05:04"  
    *               为false时, 格式如 "2000-03-05"  
    * @return 符合要求的日期字符串  
    */
    this.getSmpFormatDate = function(date, isFull) {
        var pattern = "";
        if (isFull == true || isFull == undefined) {
            pattern = "yyyy-MM-dd hh:mm:ss";
        } else {
            pattern = "yyyy-MM-dd";
        }
        return getFormatDate(date, pattern);
    }

    /**  
    *转换当前日期对象为日期字符串  
    * @param date 日期对象  
    * @param isFull 是否为完整的日期数据,  
    *               为true时, 格式如"2000-03-05 01:05:04"  
    *               为false时, 格式如 "2000-03-05"  
    * @return 符合要求的日期字符串  
    */

    this.getSmpFormatNowDate = function(isFull) {
        return getSmpFormatDate(new Date(), isFull);
    }

    /**  
    *转换long值为日期字符串  
    * @param l long值  
    * @param isFull 是否为完整的日期数据,  
    *               为true时, 格式如"2000-03-05 01:05:04"  
    *               为false时, 格式如 "2000-03-05"  
    * @return 符合要求的日期字符串  
    */

    this.getSmpFormatDateByLong = function(l, isFull) {
        return othis.getSmpFormatDate(new Date(parseInt(l)), isFull);
    }

    /**  
    *转换long值为日期字符串  
    * @param l long值  
    * @param pattern 格式字符串,例如：yyyy-MM-dd hh:mm:ss  
    * @return 符合要求的日期字符串  
    */

    this.getFormatDateByLong = function(l, pattern) {
        return getFormatDate(new Date(parseInt(l)), pattern);
    }

    /**  
    *转换日期对象为日期字符串  
    * @param l long值  
    * @param pattern 格式字符串,例如：yyyy-MM-dd hh:mm:ss  
    * @return 符合要求的日期字符串  
    */
    function getFormatDate(date, pattern) {
        if (date == undefined) {
            date = new Date();
        }
        if (pattern == undefined) {
            pattern = "yyyy-MM-dd hh:mm:ss";
        }
        return date.format1(pattern);
    }

    //特殊时间显示方式
    this.specialDateTime = function(sysTime, postdate) {
        var second = 1000;
        var minutes = second * 60;
        var hours = minutes * 60;
        var days = hours * 24;
        var months = days * 30;
        var twomonths = days * 365;
        var longtime = sysTime - postdate;

        try {
            if (longtime > days) {
                if (Math.floor(longtime / days) >= 1) {
                    return getFormatDateByLong(postdate, "MM-dd hh:mm");
                }
                return (Math.floor(longtime / days) + "天前");
            } else if (longtime > hours) {
                return (Math.floor(longtime / hours) + "小时前");
            } else if (longtime > minutes) {
                return (Math.floor(longtime / minutes) + "分钟前");
            } else if (longtime > second) {
                return (Math.floor(longtime / second) + "秒前");
            } else if (longtime <= 1000) {
                return ("1秒前");
            } else {
                return (longtime + " error ");
            }
        } catch (e) {
            return "";
        }
    }

    //特殊时间显示方式
    this.unlogTime = function(sysTime, postdate) {
        var days = 1000 * 60 * 60 * 24;
        var longtime = sysTime - postdate;

        try {
            if (longtime > days) {
                var unlog_days = Math.floor(longtime / days);
                unlog_days = unlog_days > 30 ? 30 : unlog_days;
                return (unlog_days + "天以上没登录");
            }
            else {
                return '';
            }
        } catch (e) {
            return "";
        }
    }


    //将特殊文本插入输入框中
    this.insertText = function(obj, str) {
        obj.focus();
        if (document.selection) {
            var sel = document.selection.createRange();
            sel.text = str;
        } else if (typeof obj.selectionStart == 'number' && typeof obj.selectionEnd == 'number') {
            var startPos = obj.selectionStart,
			endPos = obj.selectionEnd,
			cursorPos = startPos,
			tmpStr = obj.value;
            obj.value = tmpStr.substring(0, startPos) + str + tmpStr.substring(endPos, tmpStr.length);
            cursorPos += str.length;
            obj.selectionStart = obj.selectionEnd = cursorPos;
        } else {
            obj.value += str;
        }
    }

    //表情代码-->表情图片地址
    this.imgTran = function(str) {
        if (str == '' || str == null) {
            return "";
        }
        str = str.replace(/(^\s*)|(\s*$)/g, "");
        str = str.replace(/\[em:([\u4e00-\u9fa5A-Za-z0-9]*)]/g, '<img src=' + MPT.Config['global_icon_path'] + '/$1.gif />');
        return str;
    };

    //将输入框中的内容进行三次转义：话题转义、人名转义、表情转义
    this.escapeContent = function(_content) {
        return othis.imagesContent(othis.nickNameContent(othis.topicContent(_content)));
    };

    // 话题转义 (#xxx#)
    this.topicContent = function(str) {
        if (str == '' || str == null) {
            return "";
        }
        str = str.Trim();
        if (str.indexOf("#") == 0) {
            return str.replace(/#(.*)#/, "<a target='hashtarget' href='" + MPT.Config['hash']["topic"] + "/$1'>#$1#</a>");
        }
        return str;
    }


    // 人名转义 (@xxx)
    this.nickNameContent = function(str) {
        if (str == '' || str == null) {
            return "";
        }
        str = str.Trim();
        return str.replace(/@([\u4e00-\u9fa5A-Za-z0-9]*)\s*/g, '<a onclick="Util.goToSpace(\'$1\')">@$1</a>');
    }

    this.faces = { '挨打': 'ad', '爱情巧克力': 'aq', '芭蕾': 'bl', '摆脱': 'bt', '爆发': 'bf', '北斗神拳': 'bdsq', '背礼物': 'blw', '鄙视你': 'bsn', '必胜': 'bs', '别再逼我了': 'bz', '冰冻': 'bd', '不给糖就捣蛋': 'bg', '不行了': 'bx', '不要了拉': 'by', '财迷': 'cm', '嘲笑': 'cx', '恩恩': 'ee', '发傻': 'fs', '害羞': 'hx', '化妆': 'hz', '可爱吧': 'ka', '没们': 'mm', '你好': 'nh', '男人就是要猛': 'nr', '呕吐': 'ot', '投降': 'tx', '耶': 'ye', '野蛮女友': 'ym', '眼神杀死你': 'ys', '装可爱': 'zk' };

    // 图片转义
    this.imagesContent = function(str) {
        if (str == '' || str == null) {
            return "";
        }
        str = str.Trim();
        str = str.replace(/\[em:([\u4e00-\u9fa5A-Za-z0-9\s]*)\]/g, function(word, p1) { return "<img src='" + MPT.Config['global_faces_path'] + "/" + othis.faces[p1] + ".gif' />" });
        return str;
    }

    //通过用户昵称转向他人空间
    this.goToSpace = function(_nick) {
        if (_nick == MPT.Config["session"]["nickname"]) {
            window.location.hash = MPT.Config['hash']["myspace"];
        } else {
            var data = { "nickname": _nick };
            Backend.findUserId(data, function(_resp) {
                if (Backend.resultValidate(_resp)) {
                    var user_id = _resp.data;
                    window.location.hash = MPT.Config['hash']["uspace"] + "/" + user_id;
                } else {
                    Tip.show("访问他人空间失败");
                }
            }, function() {
                Tip.show("访问他人空间失败");
            });
        }
    };

    //将数字等级转换为图标等级
    this.transformGradeToIcon = function(grade) {

        var ICON_NAME_START = '<em class="star"></em>';
        var ICON_NAME_MOON = '<em class="moon"></em>';
        var ICON_NAME_SUN = '<em class="sun"></em>';
        var ICON_NAME_KING = '<em class="king"></em>';

        var temp = new Array();
        if (grade > 0) {
            var quotient = 0; // 商
            var remainder = 0; // 余数
            var len = 0;

            quotient = Math.floor(grade / 64);
            remainder = grade % 64;
            for (var i = 0; i < quotient; i++) {
                temp[i] = ICON_NAME_KING;
            }

            len = temp.length;
            quotient = Math.floor(grade / 16);
            remainder = remainder % 16;
            for (var i = 0; i < quotient; i++) {
                temp[len + i] = ICON_NAME_SUN;
            }

            len = temp.length;
            quotient = Math.floor(remainder / 4);
            remainder = remainder % 4;
            for (var i = 0; i < quotient; i++) {
                temp[len + i] = ICON_NAME_MOON;
            }

            len = temp.length;
            for (var i = 0; i < remainder; i++) {
                temp[len + i] = ICON_NAME_START;
            }
        }
        return temp.join('');
    };
});

MPT.addObject('SiteUtil', function(){
	
	// 重新获取验证码
	this.getRandcode = function(_img_elm)
	{
		Debug.info('[SiteUtil getRandcode] 获取验证码');
		_img_elm.src = MPT.Config.global_ctx+'/authimg?t='+Math.random();
	};
	
	this.getConstellations= function()
	{
		return {
			"1":"白羊座",
			"2":"金牛座",
			"3":"双子座",
			"4":"巨蟹座",
			"5":"狮子座",
			"6":"处女座",
			"7":"天秤座",
			"8":"天蝎座",
			"9":"射手座",
			"10":"魔羯座",
			"11":"水瓶座",
			"12":"双鱼座"
		};
	};
	
	this.getBloods= function()
	{
		return {
			"1":"O 型血",
			"2":"A 型血",
			"3":"B 型血",
			"4":"AB 型血",
			"5":"稀有血型"
		};
	};
	
	this.getLoveStatus= function()
	{
		return {
			"1":"单身",
			"2":"恋爱中",
			"3":"订婚",
			"4":"已婚",
			"5":"离异",
			"6":"其它"
		};
	};
	
	this.getGangDicts= function()
	{
		return {
			"1":"武尊",
			"2":"峨眉",
			"3":"青城",
			"4":"百花",
			"5":"仙禽"
		};
	};
	
	//获户护照等级对应的颜色
	this.getCardColor=function(){
		return {
			"1":"card1",
			"2":"card2",
			"3":"card3",
			"4":"card4",
			"5":"card6",
			"6":"card5",
			"7":"card8",
			"8":"card7",
			"9":"card10",
			"10":"card9"
		};
	};
	
	//得到地区
	this.getRegion = function(_cb_fun){
		//得到地区
		$.ajax({
			url:MPT.Config.sta_js_lib_http + '/province_city_map.js',
			dataType:'script',
			success:function(_resp){
				_resp && eval(_resp);
				_cb_fun();
			}
		});
	};
	
	this.getServerZone = function(_cb_fun)
	{
		jQuery.getScript('http://kefu.shumenol.com/js/serverzone.js', function(){
			
			// 解析数据成可用格式
			var a = eval("(" + servers + ")");
			var _t = "{";
			for(var i = 0 ; i< a.length ; i++){
				_t += "\""+a[i].id+"\":\""+a[i].name+"\",";
			}
			_t = _t.substring(0, _t.length-1);
			_t += "}";
			var areaList = eval("(" + _t + ")");
			// 执行回调
			_cb_fun(areaList);			
		});
	};	
	
	//得到服务器名称
	this.getServerGroup = function(_cb_fun,isSyn){
		jQuery.getScript('http://kefu.shumenol.com/js/serverzone.js', function(){
			
			// 解析数据成可用格式 key是大区id加上服务器id
			var a = eval("(" + servers + ")");
			var _t = "{";
			for(var i = 0 ; i< a.length ; i++){
				var groups =  a[i].groups ;
				for(var j = 0; j < groups.length; j++){
					var groupname = a[i].id+groups[j].id;
					_t += "\""+groupname+"\":\""+groups[j].name+"\",";
				}
			}
			_t = _t.substring(0, _t.length-1);
			_t += "}";
			var areaList = eval("(" + _t + ")");
			// 执行回调
			_cb_fun(areaList);			
		});
		
		
	}
});